package com.hzy;

import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class TestZookeeper {
    private static String connectString = "127.0.0.1:2181";
//            "hadoop102:2181,hadoop103:2181,hadoop104:2181";//集群模式
    private static int sessionTimeout = 2000;
    private ZooKeeper zkClient = null;

    @Before
    public void init() throws IOException {
        zkClient=new ZooKeeper(connectString, sessionTimeout, new Watcher(){
            @Override
            public void process(WatchedEvent watchedEvent) {
                System.out.println("-----------------");
                List<String> children = null;
                try {
                    children = zkClient.getChildren("/", true);
                    children.forEach(System.out::println);
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("-----------------");
            }
        });
    }
    //创建节点
    @Test
    public void createNode() throws KeeperException, InterruptedException {
        String path = zkClient.create("/hzy", "xiaogege".getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
        System.out.println(path);
    }
//    获取子节点并监控节点的变化
    @Test
    public void getDataAndWatch() throws KeeperException, InterruptedException {

        List<String> children = zkClient.getChildren("/", true);
        children.forEach(System.out::println);
        TimeUnit.MINUTES.sleep(Long.MAX_VALUE);
    }
    //判断节点是否存在
    @Test
    public void exist() throws KeeperException, InterruptedException {
        Stat exists = zkClient.exists("/sanguo", false);
        System.out.println(exists==null?"not exist":"exist");
    }
}
